<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of UploadsController
 *
 * @author pohnean
 */
class ThumbsController extends Controller {
	public $max_thumb_width = 1024;
	public $max_thumb_height = 1024;
	
	/**
	 * Specifies the access control rules.
	 * Overrides the default access control rules set in the MemberBaseController class.
	 * @return array access control rules
	 */
	public function accessRules() {
		return array(
			array(
				'allow', // allow all users to perform all actions
			),
		);
	}

	/**
	 * Generates a thumbnail
	 * @param string $user_id uuid of the user
	 * @param int $thumb_width width of the thumbnail in pixels
	 * @param int $thumb_height height of the thumbnail in pixels
	 * @param string $file basename of the requested image file
	 * @param string $ext extension of the requested image file
	 * @param string $crop_mode crop mode. 'F' for fixed aspect ratio, or 'C' for zoom crop. Defaults to 'C'
	 */
	public function actionIndex($uuid, $thumb_width, $thumb_height, $file, $ext, $crop_mode = 'C') {
		$options = array();	
		
		$party = $this->loadParty($uuid);
		if ($party === null) {
			throw new PsPageNotFoundException; // invalid party uuid
		}

		$filename = $file . '.' . $ext;
		$userfile = $this->loadUserFile($party->id, $filename);
		if ($userfile === null) {
			throw new PsPageNotFoundException; // invalid userfile
		}

		if (!file_exists($userfile->getRealPath())) {
			throw new PsPageNotFoundException; // source file not found
		}
		
		if ($thumb_width > $this->max_thumb_width) {
			die('Max thumb width is ' . $this->max_thumb_width);
		}
		
		if ($thumb_height > $this->max_thumb_height) {
			die('Max thumb height is ' . $this->max_thumb_height);
		}
		
		if ($crop_mode == 'F') {
			$options['far'] = 'C';
		} else {
			$options['zc'] = 'C';
		}		
			
		$userfile->generateThumbnail($thumb_width, $thumb_height, $options, UserFile::THUMBNAIL_OUTPUT_TO_BROWSER);
	}

	/**
	 * @param string $uuid uuid of the party
	 * @return Party
	 */
	public function loadParty($uuid) {
		return Party::model()->findByAttributes(array(
					'uuid' => $uuid
		));
	}

	/**
	 * @param string $owner_party_id
	 * @param string $realfilename
	 * @return UserFile
	 */
	public function loadUserFile($owner_party_id, $realfilename) {
		return UserFile::model()->findByAttributes(array(
					'owner_party_id' => $owner_party_id,
					'realfilename' => $realfilename
		));
	}

}

?>
